package com.bjpower.springboot.connection;

import org.junit.Test;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author: yg
 * @create 2025-01-23 - 18:40
 * @
 */
public class ConnectionTest {
    //方式一
    @Test
    public void testConnection1() throws SQLException {
        Driver driver = new com.mysql.cj.jdbc.Driver();
        String url = "jdbc:mysql://localhost:3306/ninja_nation?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8";
        //将用户名密码封装到Properties中
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "123456");

        Connection conn = driver.connect(url, info);
        System.out.println(conn);
    }
    @Test
    public void testConnection2() throws Exception {
        //1.获取Driver实现类对象实例，使用反射
        Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver = (Driver) clazz.newInstance();
        String url = "jdbc:mysql://localhost:3306/ninja_nation?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8";
        //将用户名密码封装到Properties中
        Properties info = new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "123456");
        Connection conn = driver.connect(url, info);
        System.out.println(conn);
    }
    //用DriverManager替换Driver
    @Test
    public void testConnection3() throws Exception {
        String url = "jdbc:mysql://localhost:3306/ninja_nation?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8";
        String user = "root";
        String password = "123456";
        Class.forName("com.mysql.cj.jdbc.Driver");
//        Driver driver = (Driver) clazz.newInstance();
//        //注册驱动
//        DriverManager.registerDriver(driver);
        //获取连接
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);
    }
    //最红版，将数据库连接信息生命在配置文件中，通过读取配置文件的方式获取连接
    @Test
    public void testConnection4() throws Exception {
        InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties pros = new Properties();
        pros.load(is);
        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        String url = pros.getProperty("url");
        String driver = pros.getProperty("driver");
        Class.forName(driver);
        Connection conn = DriverManager.getConnection(url, user, password);
        System.out.println(conn);

    }

}
